const DECKS_KEY = 'anki_decks'
const CARDS_KEY = 'anki_cards'

export const storage = {
  getDecks() {
    if (typeof window === 'undefined') return []
    const decks = localStorage.getItem(DECKS_KEY)
    return decks ? JSON.parse(decks) : []
  },
  deleteDeck(deckId) {
    if (typeof window === 'undefined') return
    const decks = this.getDecks().filter(deck => deck.id !== deckId)
    localStorage.setItem(DECKS_KEY, JSON.stringify(decks))
    this.deleteCardByDeck(deckId)
  },
  saveDeck(deck) {
    if (typeof window === 'undefined') return
    const decks = this.getDecks()
    const index = decks.findIndex(d => d.id === deck.id)
    
    if (index > -1) {
      decks[index] = deck
    } else {
      decks.push(deck)
    }
    
    localStorage.setItem(DECKS_KEY, JSON.stringify(decks))
  },

  getCards() {
    if (typeof window === 'undefined') return []
    const cards = localStorage.getItem(CARDS_KEY)
    return cards ? JSON.parse(cards) : []
  },

  getCardsByDeck(deckId) {
    if (typeof window === 'undefined') return []
    return this.getCards().filter(card => card.deck === deckId)
  },
  deleteCardByDeck(deckId){
    if (typeof window === 'undefined') return []
    const cards = this.getCards().filter(card => card.deck !== deckId)
    localStorage.setItem(CARDS_KEY, JSON.stringify(cards))
  }
  ,

  saveCard(card) {
    if (typeof window === 'undefined') return
    const cards = this.getCards()
    const index = cards.findIndex(c => c.id === card.id)
    
    if (index > -1) {
      cards[index] = card
    } else {
      cards.push(card)
    }
    
    localStorage.setItem(CARDS_KEY, JSON.stringify(cards))
  },

  deleteCard(cardId) {
    if (typeof window === 'undefined') return
    const cards = this.getCards().filter(card => card.id !== cardId)
    localStorage.setItem(CARDS_KEY, JSON.stringify(cards))
  }
}